﻿using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace LitTools
{
    /// <summary>
    /// 使用PlayerPref进行存档
    /// 优点，不依赖任何第三方库
    /// 缺点，不能序列化字典
    /// </summary>
    public class PlayerPrefSave : SaveStrategy
    {
        public override T LoadData<T>()
        {
            string saveKey = typeof(T).FullName;
            T data = new();
            if (PlayerPrefs.HasKey(saveKey))
            {
                string json = PlayerPrefs.GetString(saveKey, "");
                try
                {
                    json = AESEncryptUtility.DecryptString(json, StorageModule.EncryptKey, StorageModule.EncryptIV);
                    data = JsonUtility.FromJson<T>(json);
                }
                catch
                {
                    Debug.LogError("[PlayerPrefSave] LoadData 读取存档失败，使用默认值");
                    data = data.GetDefaultValue();
                }
            }
            else
            {
                Debug.LogError($"[PlayerPrefSave] LoadData key:{saveKey}为空，使用默认值");
                data = data.GetDefaultValue();
            }
            return data;
        }

        public override void ClearData<T>()
        {
            string saveKey = typeof(T).FullName;
            if (PlayerPrefs.HasKey(saveKey))
            {
                PlayerPrefs.DeleteKey(saveKey);
                Debug.Log($"[PlayerPrefSave] ClearData 删除数据:{saveKey}");
            }
            else
            {
                Debug.Log($"[PlayerPrefSave] ClearData 数据不存在:{saveKey}");
            }
        }

        public override void SaveData<T>(T data)
        {
            string saveKey = typeof(T).FullName;
            string json = JsonUtility.ToJson(data);
            string encryptStr = AESEncryptUtility.EncryptString(json, StorageModule.EncryptKey, StorageModule.EncryptIV);
            PlayerPrefs.SetString(saveKey, encryptStr);
            Debug.Log($"[PlayerPrefSave] SaveData 保存数据:{saveKey} \n {json}");
        }

        public override void WriteToDisk()
        {
            PlayerPrefs.Save();
            Debug.Log($"[PlayerPrefSave] WriteToDisk 写入数据到硬盘");
        }
    }
}